package com.hjqjl.whdemo.utils;

import java.io.InputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;

public class ImageUtil {

    /**
     *
     * 按指定宽度和高度缩放图片,不保证宽高比例
     *
     * @param bitmap
     *
     * @param w
     *
     * @param h
     *
     * @return
     */

    public static Bitmap zoomBitmap(Bitmap bitmap, float w, float h) {
        if (bitmap == null) {
            return null;
        }
        // 获得图片的宽高
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Matrix matrix = new Matrix();
        // 计算缩放比例
        float scaleWidht = ((float) w / width);
        float scaleHeight = ((float) h / height);
        // 取得想要缩放的matrix参数
        matrix.postScale(scaleWidht, scaleHeight);
        // 得到新的图片
        Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height,
                matrix, true);
        return newbmp;
    }

    /**
     *
     * 以最省内存的方式读取本地资源的图片
     *
     * @param context
     * @param resId
     * @return
     **/
    public static Bitmap readBitMap(Context context, int resId) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true; // 获取资源图片
        InputStream is = context.getResources().openRawResource(resId);
        return BitmapFactory.decodeStream(is, null, opt);
    }

    /**
     *
     * 以最省内存的方式读取本地资源的图片
     * bitmap = ImageUtil.readBitMap(XingxingShow.class.getClassLoader(), "res/drawable-hdpi/xingxingshow.png");
     * @return
     **/
    public static Bitmap readBitMap(ClassLoader classLoader, String path) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true; // 获取资源图片
        InputStream is = classLoader.getResourceAsStream(path);
        return BitmapFactory.decodeStream(is, null, opt);
    }
    /**
     * 图片资源回收
     *
     * @param bitmap
     */
    public static void bitmapRecycle(Bitmap bitmap) {
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
            bitmap = null;
//			System.gc();
        }
    }
}
